package caidan;

import caidan.data.CategoryData;
import jinyilw.common.SettingTools;
import jinyilw.common.TextTools;
import jinyilw.common.app.AppConfig;
import jinyilw.common.file.FileTools;
import jinyilw.swing.ScreenTools;
import jinyilw.swing.hint.SwingHinter;
import jinyilw.swing.i18n.LanguageTools;
import jinyilw.swing.rlaf.utils.RLafUtils;
import jinyilw.swing.visuals.window.ScaleSplashWindow;
import jinyilw.tools.h2db.DBConfig;
import jinyilw.tools.net.NetConfig;

import javax.swing.JOptionPane;
import java.awt.EventQueue;
import java.io.File;

public class MainApp
{
	public static final int appVersion = 401;
	public static final String APP_NAME = "智 能 食 谱 管 理 系 统 4.1(测试版)";
	public static final int MAX_ROW = 10;
	public static String appName = APP_NAME;
	public static String userName = "";

	public static final boolean is4211 = true;
	public static final String[] dayStrings = {"星期一", "星期二", "星期三", "星期四",
			"星期五", "星期六", "星期日"};
	public static final String[] mealStrings = {"早餐", "午餐", "晚餐"};
	public static final String[] names = {"主食", "荤菜", "半荤", "素菜", "汤粥", "水果",
			"杂粮"};
	public static final boolean[] isMainFoods = {true, false, false, false,
			true, false, false};
	public static final boolean[] isMainDishes = {false, true, false, false,
			true, false, false};
	public static final String imagePath = "food/";
	public static final String[] iNames = {"staple.png", "meat.png",
			"half_meat.png", "vegetable.png", "soup.png", "fruit.png",
			"cheeseburger.png"};
	public static final int[] ns1 = {3, 1, 2, 1, 1, 1, 1};
	public static final int[] ns2 = {2, 2, 2, 2, 1, 1, 1};
	public static final int[] CHOOSE_NUMS = is4211 ? ns1 : ns2;
	public static final int[] COL_NUMS = {4, 3, 3, 3, 3, 2, 0};
	public static final int[] breakfastNums = CHOOSE_NUMS.clone();
	public static final int[] otherNums = CHOOSE_NUMS.clone();
	public static final int[] cols = COL_NUMS.clone();

	public static final String columnKey = "columns";
	public static final String categoryNameKey = "categoryName";
	public static final String bChooseNumsKey = "breakfastChooseNums";
	public static final String oChooseNumsKey = "otherChooseNums";
	public static final int[] kIndexes = {0, 1, 2, 3, 4, 5, 6};

	public static String[] categoryNames = names;
	public static int[] breakfastChooseNums = breakfastNums;
	public static int[] otherChooseNums = otherNums;
	public static int[] columns = cols;
	public static String[] imageNames = iNames;
	public static int[] keyIndexes = kIndexes;

	public static int maxRow = MAX_ROW;
	public static int chooseRow = MAX_ROW;
	public static int peopleNum = 80;

	private static CategoryData[] categoryDatas;
	public static int breakfastMaxChooseNum = 0, otherMaxChooseNum = 0;
	public static int maxChooseNum = 0;
	public static int maxColumn = 0;

	private static File countDataFolder, menuDataFolder, outputFolder;
	private static File lastDataFile;

	public static MainFrame frame;
	private static LagerView lagerView;
	private static SettingView settingView;
	private static OneWeekView oneWeekView;
	private static FavoriteView favoriteView;

	static boolean isFullScreenMode = false;
	static boolean isExtendMode = false;
	static int extendWW = ScreenTools.getDefaultScreenSize().width / 16;
	static int extendHH = (int) (extendWW * 0.85);
	static int extendSS = (int) (extendWW * 0.067);

	public static void main(String[] args)
	{
		AppConfig.set(appVersion, "智能食谱管理系统", "RecipeApp.exe",
				"data", "caidan.ini", "start.jpg");
		NetConfig.set("Net.ini", false, "localhost",
				11137, 11100);
		NetConfig.set("24.159.80.196", 11000);
		DBConfig.set("Database.ini", false,
				"localhost", 9080, "~/.database/caidan", "root", "");

		File splashFile = FileTools.getUserFile(AppConfig.splashPicture);

		if (splashFile != null && splashFile.isFile())
			new ScaleSplashWindow(splashFile)
					.launch();
		SwingHinter.init();
		initSetting();
		initUpdate();
		// NetworkConfig.DEBUG = true;
		LanguageTools.setLanguageSettingEnable(false);
		// UITools.initRLookAndFeel();
		MainApp.getCategoryDatas();

		EventQueue.invokeLater(new Runnable()
		{
			@Override
			public void run()
			{
				frame = new MainFrame();
				if (TextTools.isBlank(userName))
				{
					String result = JOptionPane.showInputDialog(null,
							"设置单位或用户名：", "初始化设置", JOptionPane.QUESTION_MESSAGE);
					if (!TextTools.isBlank(result))
					{
						MainApp.setUserName(result);
						frame.sendUserInfo();
					}
				}
				frame.setVisible(true);

				String dataFilePath = SettingTools
						.getDefaultString("dataFilePath", "null");
				if (!"null".equals(dataFilePath))
				{
					oneWeekView = new OneWeekView(frame);
					oneWeekView.setEditable(true);
					oneWeekView.setTitle("编 辑 食 谱");
					oneWeekView.readDataFromFile(new File(dataFilePath));
					oneWeekView.showView();
					SettingTools.putDefaultSettingData("dataFilePath", "null");
				}
				AppConfig.addAppExitedOperator((Object o) ->
				{
					saveData();
				});
			}
		});
	}
	private static void initUpdate()
	{
		File src = FileTools.getUserFile("newFood");
		if (!src.exists() || !FileTools.canWrite(src))
			return;
		File forder = NetConfig.isServer()
				? FileTools.createDirectory(AppConfig.getAppDataFolder(), "serverData")
				: FileTools.createDirectory(AppConfig.getAppDataFolder(), "clientData");

		File des = new File(forder, "newFood");
		FileTools.copyFolder(src, des);
		FileTools.deleteFolder(src);
		src = FileTools.getUserFile("newFoodInNet");
		des = new File(forder, "newFoodInNet");
		FileTools.copyFolder(src, des);
		FileTools.deleteFolder(src);
		if (NetConfig.isServer())
		{
			src = new File(AppConfig.getSettingsFolder(), "serverNewFood");
			des = new File(forder, "serverNewFood");
			FileTools.copyFile(src, des);
			src.delete();
		} else
		{
			src = new File(AppConfig.getSettingsFolder(), "clientNewFood");
			des = new File(forder, "clientNewFood");
			FileTools.copyFile(src, des);
			src.delete();
			src = new File(AppConfig.getSettingsFolder(), "suggest");
			des = new File(forder, "suggest");
			FileTools.copyFile(src, des);
			src.delete();
		}
	}

	private MainApp()
	{
	}

	private static void initSetting()
	{
		int l = 0;
		for (int i = 0; i < columns.length; i++)
		{
			columns[i] = SettingTools.getDefaultInt(columnKey + i, cols[i]);
			categoryNames[i] = SettingTools
					.getDefaultString(categoryNameKey + i, names[i]);
			breakfastChooseNums[i] = SettingTools
					.getDefaultInt(bChooseNumsKey + i, breakfastNums[i]);
			otherChooseNums[i] = SettingTools.getDefaultInt(oChooseNumsKey + i,
					otherNums[i]);
			if (columns[i] > 0)
			{
				l++;
				if (breakfastChooseNums[i] >= columns[i])
					columns[i] = breakfastChooseNums[i] + 1;
				if (otherChooseNums[i] >= columns[i])
					columns[i] = otherChooseNums[i] + 1;
			}
		}
		if (l < columns.length)
		{
			breakfastChooseNums = new int[l];
			otherChooseNums = new int[l];
			categoryNames = new String[l];
			imageNames = new String[l];
			columns = new int[l];
			keyIndexes = new int[l];
			int ii = 0;
			for (int i = 0; i < cols.length; i++)
			{
				if (cols[i] > 0)
				{
					columns[ii] = cols[i];
					breakfastChooseNums[ii] = breakfastNums[i];
					otherChooseNums[ii] = otherNums[i];
					categoryNames[ii] = names[i];
					imageNames[ii] = iNames[i];
					keyIndexes[ii] = kIndexes[i];
					ii++;
				}
			}
		}

		for (int n : breakfastChooseNums)
			breakfastMaxChooseNum += n;
		for (int n : otherChooseNums)
			otherMaxChooseNum += n;
		maxChooseNum = Math.max(breakfastMaxChooseNum, otherMaxChooseNum);
		for (int n : columns)
			maxColumn += n;
		chooseRow = maxRow = SettingTools.getDefaultInt("maxRow", maxRow);
		appName = SettingTools.getDefaultString("appName", appName);
		userName = SettingTools.getDefaultString("userName", userName);
		peopleNum = SettingTools.getDefaultInt("peopleNum", peopleNum);
		isFullScreenMode = SettingTools.getDefaultBool("isFullScreenMode",
				isFullScreenMode);
		isExtendMode = SettingTools.getDefaultBool("isExtendMode",
				isExtendMode);
		createDirectory();
	}

	public static File getCountDataFolder()
	{
		if (countDataFolder == null)
			countDataFolder = new File(AppConfig.getAppDataFolder(), "统计数据");
		return countDataFolder;
	}

	public static File getFoodDataForder()
	{
		if (menuDataFolder == null)
			menuDataFolder = new File(AppConfig.getAppDataFolder(), "食谱数据");
		return menuDataFolder;
	}

	public static File getOutputFolder()
	{
		if (outputFolder == null)
			outputFolder = new File(AppConfig.getAppDataFolder(), "导出菜单");
		return outputFolder;
	}

	public static File getLastDataFile()
	{
		if (lastDataFile == null)
			lastDataFile = new File(AppConfig.getSettingsFolder(),
					"last.data");
		return lastDataFile;
	}

	public static boolean isSelectBreakfast()
	{
		if (frame == null)
			return true;
		return frame.isSelectBreakfast();
	}

	static void createDirectory()
	{
		getCountDataFolder().mkdirs();
		getFoodDataForder().mkdirs();
		getOutputFolder().mkdirs();
	}

	static void resetData()
	{
		for (CategoryData data : categoryDatas)
			data.reset();
		RLafUtils.restartApplication();
	}

	static void saveData()
	{
		for (CategoryData data : categoryDatas)
			data.saveWhenExit();
	}

	static void resetOrigin()
	{
		for (int i = 0; i < CHOOSE_NUMS.length; i++)
		{
			SettingTools.putDefaultSettingData(bChooseNumsKey + i,
					CHOOSE_NUMS[i]);
			SettingTools.putDefaultSettingData(oChooseNumsKey + i,
					CHOOSE_NUMS[i]);
		}
		for (int i = 0; i < COL_NUMS.length; i++)
			SettingTools.putDefaultSettingData(columnKey + i, COL_NUMS[i]);
		RLafUtils.restartApplication();
	}

	static void setAppName(String appName)
	{
		MainApp.appName = appName;
		SettingTools.putDefaultSettingData("appName", appName);
	}

	public static void setMaxRow(int maxRow)
	{
		MainApp.maxRow = chooseRow = maxRow;
		SettingTools.putDefaultSettingData("maxRow", maxRow);
	}

	public static void setUserName(String userName)
	{
		if (userName != null)
		{
			MainApp.userName = userName;
			SettingTools.putDefaultSettingData("userName", userName);
		}
	}

	public static void setPeopleNum(int peopleNum)
	{
		MainApp.peopleNum = peopleNum;
		SettingTools.putDefaultSettingData("peopleNum", peopleNum);
	}

	public static String getUserName()
	{
		return userName;
	}

	public static void setFullScreenMode(boolean b)
	{
		MainApp.isFullScreenMode = b;
		SettingTools.putDefaultSettingData("isFullScreenMode", b);
	}

	public static void setExtendMode(boolean b)
	{
		MainApp.isExtendMode = b;
		SettingTools.putDefaultSettingData("isExtendMode", b);
	}

	public static void setCategoryName(String name, int index)
	{
		names[index] = name;
		SettingTools.putDefaultSettingData(categoryNameKey + index, name);
	}

	public static synchronized CategoryData[] getCategoryDatas()
	{
		if (categoryDatas != null)
			return categoryDatas;

		categoryDatas = new CategoryData[categoryNames.length];
		Thread[] threads = new Thread[categoryDatas.length];
		for (int i = 0; i < threads.length; i++)
		{
			final int ii = i;
			threads[i] = new Thread(() ->
			{
				categoryDatas[ii] = new CategoryData(categoryNames[ii],
						breakfastChooseNums[ii], otherChooseNums[ii],
						keyIndexes[ii], ii);
			});
		}
		for (Thread t : threads)
			t.start();
		try
		{
			for (Thread t : threads)
				t.join();
		} catch (InterruptedException e)
		{
			e.printStackTrace();
		}
		return categoryDatas;
	}

	public static LagerView getLagerView()
	{
		if (lagerView == null)
			lagerView = new LagerView(frame);
		return lagerView;
	}

	public static SettingView getSettingView()
	{
		if (settingView == null)
			settingView = new SettingView(frame);
		return settingView;
	}

	public static OneWeekView getOneWeekView()
	{
		if (oneWeekView == null)
			oneWeekView = new OneWeekView(frame);
		return oneWeekView;
	}

	public static FavoriteView getFavoriteView()
	{
		if (favoriteView == null)
			favoriteView = new FavoriteView(frame);
		return favoriteView;
	}
}
